using UnityEngine;
using UnityEngine.UI;

public class FoodMaker : MonoBehaviour
{
    private static FoodMaker _instance;
    public static FoodMaker Instance
    {
        get { return _instance; }
    }

    public int xlimit = 21;
    public int ylimit = 10;
    public int xoffset = 7;
    public GameObject foodPrefab;
    public GameObject rewardPrefab;
    public Sprite[] foodSprites;
    private Transform foodHolder;
    

    private void Awake()
    {
        _instance = this;
    }

    void Start()
    {
        foodHolder = GameObject.Find("FoodHolder").transform;
        MakeFood(false);
    }

    private int[] GetBorn()
    {
        int x = Random.Range(-xlimit + xoffset, xlimit);
        int y = Random.Range(-ylimit, ylimit);

        bool isRepeat = true;
        while (isRepeat)
        { 
            x = Random.Range(-xlimit + xoffset, xlimit); 
            y = Random.Range(-ylimit, ylimit);
            //Vector3 tmp = new Vector3(30 * x, 30 * y, 0);
            for (int i = SnakeHead.Instance.bodyList.Count - 1; i >= 0; i--)
            {
                int _x = (int)SnakeHead.Instance.bodyList[i].localPosition.x;
                int _y = (int)SnakeHead.Instance.bodyList[i].localPosition.y;
                _x = (_x % 5 == 0) ? _x : (_x + ((_x > 0) ? 1 : -1));
                _y = (_y % 5 == 0) ? _y : (_y + ((_y > 0) ? 1 : -1));
                //Debug.Log(_x + "<->" + _y + "||" + x*30 + "<->" + (y * 30 - 15));
                if ((30 * x == _x) && (30 * y - 15 == _y))
                {
                    isRepeat = false;
                    Debug.Log("isRepeat == false");
                    break;
                }
            }
            isRepeat = !isRepeat;
        }
        //Debug.Log("isRepeat == ture");
        return new int[] { x, y };
    }

    public void MakeFood(bool isReward)
    {
        int index = Random.Range(0, foodSprites.Length);
        GameObject food = Instantiate(foodPrefab);
        food.GetComponent<Image>().sprite = foodSprites[index];
        food.transform.SetParent(foodHolder, false);
        int[] tmp = GetBorn();
        int x = tmp[0];
        int y = tmp[1];

        //int x = Random.Range(-xlimit + xoffset, xlimit);
        //int y = Random.Range(-ylimit, ylimit);

        food.transform.localPosition = new Vector3(x * 30, y * 30 - 15, 0);

        if(isReward)
        {
            GameObject reward = Instantiate(rewardPrefab);
            reward.transform.SetParent(foodHolder, false);
            tmp = GetBorn();
            x = tmp[0];
            y = tmp[1];
            //x = Random.Range(-xlimit + xoffset, xlimit);
            //y = Random.Range(-ylimit, ylimit);
            reward.transform.localPosition = new Vector3(x * 30, y * 30 - 15, 0);
        }
    }
}
